package wakeup.server.persistence;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.hibernate.Session;

import wakeup.server.model.Track;

public class TrackDAO {
	
	List<Track> tracks;
	private final Logger logger = Logger.getLogger("logger");
	
	public TrackDAO() {
		tracks = new ArrayList<Track>();
	}
	
	public void loadTracks() {
        Session session = HibernateUtil.getSessionFactory().openSession();
 
        session.beginTransaction();
        
        logger.log(Level.INFO, "Chargement des tracks depuis la base MySQL");
        tracks.clear();
        tracks = (List<Track>)session.createQuery("from Track").list();
        
        session.close();
	}
	
	public List<Track> getTracks() {
		if (tracks.isEmpty()) loadTracks();
		return tracks;
	}
	
	public Track getTrack(Date date) {
		loadTracks();
		
		for (Track track : tracks) {
			if (track.getBroadcastDate().getDate() == date.getDate() &&
				track.getBroadcastDate().getMonth() == date.getMonth() &&
				track.getBroadcastDate().getYear() == date.getYear()) return track;
		}
		logger.log(Level.INFO, "Aucune ressource correspondant à la date donnée");
		
		return tracks.get(0);
	}

}
